//
//  NewsDetailsTableViewController.m
//  FootBallTest_huang
//
//  Created by lanou3g on 15/5/30.
//  Copyright (c) 2015年 lanou3g.com. All rights reserved.
//

#import "NewsDetailsTableViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "NewsModle.h"
#import "NewsDetailsModel.h"
#import "NewsDetailsCommentsModle.h"
#import "NewsDetailsOneTableViewCell.h"
#import "NewsDetailsTwoTableViewCell.h"
#import "NewsDetailsThreeTableViewCell.h"
#import "NewsTableViewController.h"
#import "UIImageView+WebCache.h"
@interface NewsDetailsTableViewController ()

{
    NSString * _currentElementName;
    CGFloat cell2Height;
}

@property (nonatomic,assign) BOOL isParse;
@end

@implementation NewsDetailsTableViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    cell2Height = 100;
    self.isParse = NO;
    [self stringWithFormat:[NSString stringWithFormat:@"%@%@",self.detailWeb,self.newsModle.nid]];

}


- (void)stringWithFormat:(NSString *)url
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    self.newsDetailsModleArray = [NSMutableArray array];
    
    self.newsDetailsCommentsModleArray = [NSMutableArray array];
    
    // 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情
    __weak NewsDetailsTableViewController * NDTVC = self;
    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject == nil) {
            return ;
        }
        NSMutableDictionary * BigDic = responseObject;
        
        NSMutableDictionary * dic = [BigDic objectForKey:@"result"];

        self.newsDetailsModle = [[NewsDetailsModel alloc] init];
        
        [_newsDetailsModle setValuesForKeysWithDictionary:dic];
        
        [NDTVC.newsDetailsModleArray addObject:_newsDetailsModle];
        
        NSMutableArray * commentArray = [dic objectForKey:@"light_comments"];

        for (NSMutableDictionary * smallDic in commentArray) {
            
          NewsDetailsCommentsModle * newsDetailsCommentsModle = [[NewsDetailsCommentsModle alloc] init];
            
          [newsDetailsCommentsModle setValuesForKeysWithDictionary:smallDic];
            
          [NDTVC.newsDetailsCommentsModleArray addObject:newsDetailsCommentsModle];
          
        }
        
         NDTVC.isParse =YES;
        
        [NDTVC.tableView reloadData];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
//
    if (self.isParse == YES) {

    return (2+_newsDetailsCommentsModleArray.count);
        
    }else{
        
        return 0;
        
    }
    
}



//切割
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    tableView.frame =CGRectMake(0, 0, self.view.frame.size.width,CGRectGetHeight(tableView.window.frame)-105);
    
}


//时间搓转化成多少分钟前
- (NSString *)timeInfoWithDateString:(NSString *)dateString {
    
    
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    //    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate* date = [inputFormatter dateFromString:dateString];
//    NSLog(@"date = %@", date);
    
    
    
    // 把日期字符串格式化为日期对象
    //    NSDate *date = [NSDate dateFromString:dateString withFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *curDate = [NSDate date];
    NSTimeInterval time = -[date timeIntervalSinceDate:curDate];
    
    
    NSTimeInterval retTime = 1.0;
    // 小于一小时
    if (time < 3600) {
        retTime = time / 60;
        retTime = retTime <= 0.0 ? 1.0 : retTime;
        return [NSString stringWithFormat:@"%.0f分钟前", retTime];
    }
    // 小于一天，也就是今天
    else if (time < 33600 * 24) {
        retTime = time / 3600;
        retTime = retTime <= 0.0 ? 1.0 : retTime;
        return [NSString stringWithFormat:@"%.0f小时前", retTime];
    }
    // 昨天
    else if (time < 33600 * 224 * 2) {
        return @"昨天";
    }
    return nil;
}




- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NewsDetailsModel * newsDetailsModle = _newsDetailsModleArray[0];
//    NSLog(@"%@",newsDetailsModle);
    if (indexPath.row == 0) {
        [self.tableView registerNib:[UINib nibWithNibName:@"NewsDetailsOneTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"oneCell"];
        
        NewsDetailsOneTableViewCell * cell = [self.tableView dequeueReusableCellWithIdentifier:@"oneCell"];
        
        cell.title.text = newsDetailsModle.title;
        
        
        
        NSString * returnDateString=nil;
        
        NSDate *confromTimesp =[NSDate dateWithTimeIntervalSince1970:[newsDetailsModle.addtime integerValue]];
        NSDate *nowdate = [NSDate date];
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"YYYYMMddHHmmss"];
        NSString *nowdateString = [formatter stringFromDate:nowdate];
        
        NSString *addtime = [formatter stringFromDate:confromTimesp];
        
        NSTimeInterval nowDateInterval = [[NSDate date] timeIntervalSince1970];
        
        NSTimeInterval twoTimeInterval = nowDateInterval - [newsDetailsModle.addtime integerValue];
        
        
        NSInteger  nowDateInteger = [nowdateString integerValue];
        NSInteger  addTimeInteger = [addtime integerValue];
        NSInteger  twoTimeInterV = nowDateInteger - addTimeInteger;
        if (twoTimeInterV>2000000) {
            returnDateString = addtime;
//            NSLog(@"%@",addtime);
            
        }else if(twoTimeInterV>1000000&&twoTimeInterV<2000000){
            
            returnDateString = @"昨天";
//            NSLog(@"昨天");
            
        }else {
            
            if (twoTimeInterval>3600) {
                NSInteger fffff = (NSInteger)twoTimeInterval;
                NSInteger hour =fffff/3600;
                returnDateString = [NSString stringWithFormat:@"%ld 小时之前",hour];
            }else{
                
                NSInteger minit =(NSInteger)twoTimeInterval%60;
                returnDateString = [NSString stringWithFormat:@"%ld 分钟之前",minit];
                
            }
            
            
            
        }
        
        cell.addtime.text =returnDateString;
        
        
        
        
        //调用时间搓转化成多少分钟前
//        cell.addtime.text = [self timeInfoWithDateString:newsDetailsModle.addtime];
        
        cell.origin.text = newsDetailsModle.origin;
        
        return cell;
        

    }else if(indexPath.row == 1){
        
        [self.tableView registerNib:[UINib nibWithNibName:@"NewsDetailsTwoTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"twoCell"];
        
        NewsDetailsTwoTableViewCell * cell = [self.tableView dequeueReusableCellWithIdentifier:@"twoCell"];
        
        //调用NewsDetailsTwoTableViewCell里面的方法(webView)
        [cell setNewsDetailModel:newsDetailsModle];
        cell.target = self;
        cell.action = @selector(refreshCellHeight);
        
        [cell.img sd_setImageWithURL:[NSURL URLWithString:newsDetailsModle.img_m] placeholderImage:[UIImage imageNamed:@"placeHold"]];
        
           return cell;
        
    }else {
        
        NewsDetailsCommentsModle * newsDetailsCommentsModle = _newsDetailsCommentsModleArray[indexPath.row-2];
        
       [self.tableView registerNib:[UINib nibWithNibName:@"NewsDetailsThreeTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"threeCell"];
        
        NewsDetailsThreeTableViewCell * cell = [self.tableView dequeueReusableCellWithIdentifier:@"threeCell"];
        
        cell.user_name.text = newsDetailsCommentsModle.user_name;
        cell.create_time.text = newsDetailsCommentsModle.create_time;
        cell.content.text = newsDetailsCommentsModle.content;
        cell.light_count.text =newsDetailsCommentsModle.light_count;
        
        
        
        return cell;
    }
    
    return nil;
}


-(void)refreshCellHeight{
    
    NewsDetailsTwoTableViewCell * newsDCell = (NewsDetailsTwoTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    cell2Height = newsDCell.height+10;
    [self.tableView reloadData];
    
}


#pragma mark---计算文本高度
- (CGFloat)textLabelHeight:(NSString *)text
{
    
    CGSize size = CGSizeMake(self.view.frame.size.width, 10000000);
    
    NSDictionary * dic = @{NSFontAttributeName:[UIFont systemFontOfSize:16.0]};
    
    CGRect rect = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:dic context:nil];
    
    return rect.size.height;
    
}


#pragma mark---设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewsDetailsModel * newsDetailsModel = _newsDetailsModleArray[0];
    
    if (indexPath.row == 0) {
        
        CGFloat heingt = [self textLabelHeight:newsDetailsModel.title];
        
        if (heingt+40 < 75) {
            
            return 75;
            
        }
        return heingt+40;
        
    }else if (indexPath.row == 1){

//        NSLog(@"%.f",cell2Height);
        if (cell2Height+240 < 300) {
            
            return 300;
            
        }
        return cell2Height+240;
        
    }else{
        
        NewsDetailsCommentsModle * newsDetailsCommentsModle = _newsDetailsCommentsModleArray[indexPath.row-2];
        
        CGFloat height = [self textLabelHeight:newsDetailsCommentsModle.content];
        
        if (height+80<110) {
            
            return 110;
            
        }
        return height+80;
    }
    
    
}


//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
//{
//    
//}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here, for example:
    // Create the next view controller.
    <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:<#@"Nib name"#> bundle:nil];
    
    // Pass the selected object to the new view controller.
    
    // Push the view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
